/*
 *
 * @ProjectName:    my_umi_app
 * @Package:
 * @ClassName:      blogger
 * @Description:    博主介绍
 * @Author:         SuPeiSen
 * @CreateDate:     2021/3/4 2:40 下午
 * @UpdateDate:     2021/3/4 2:40 下午
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */

import { Button, Form, message } from 'antd';
import { AppConfig, AppImageUrl } from '@/config/app_config';
import { Editor } from '@tinymce/tinymce-react';
import { uploadFileToQiNiuApi } from '@/service/upload_api';
import React, { useEffect, useRef, useState } from 'react';
import {
  GetBloggerInfoApi,
  UpdateBloggerInfoApi,
} from '@/service/blog_setting_api';

// Tiny配置
const initToolbar1 =
  'undo redo |  styleselect | bold italic | alignleft aligncenter alignright alignjustify | ' +
  'bullist numlist outdent indent | link image | print preview  | ' +
  'forecolor backcolor emoticons | fullscreen help';

// 初始化插件
const initPlugins = [
  'codesample image',
  'advlist autolink link image lists charmap print preview hr anchor pagebreak',
  'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
  'table emoticons template paste help',
];

// Form表单一些样式配置
const formItemLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 },
};

const buttonLayout = {
  wrapperCol: { offset: 2, span: 22 },
};

export default () => {
  // 使用useForm创建form对象
  const [form] = Form.useForm();
  // button-loading
  const [btnLoading, setBtnLoading] = useState<boolean>(false);
  // 保存内容
  const contentRef = useRef<{ value: string }>({ value: '' });

  useEffect(() => {
    GetBloggerInfoApi().then((model) => {
      if (model.success) {
        const bloggerContent = model.data!.data.blogger_content;
        contentRef.current.value = bloggerContent;
        form.setFieldsValue({
          blogger_content: bloggerContent,
        });
      }
    });
  }, []);

  // 提交表单
  const postContent = async () => {
    setBtnLoading(true);
    UpdateBloggerInfoApi(contentRef.current.value)
      .then((success) => {
        if (success) {
          message.success('更新成功');
        } else {
          message.error('更新失败');
        }
      })
      .finally(() => setBtnLoading(false));
  };
  return (
    <div className="add_article_main_div">
      <Form {...formItemLayout} onFinish={postContent} form={form}>
        {/*富文本*/}
        <Form.Item
          label="内容"
          name="blogger_content"
          // (玄学哈哈哈哈)加上这一段就不会报错了
          // Failed prop type: Invalid prop `value` of type `object` supplied to `Editor`, expected `string`.
          normalize={(value, prevValue, allValues) => {}}
          initialValue={contentRef.current.value}
          style={{ width: '80%' }}
        >
          <Editor
            apiKey={AppConfig.TinyEditKey}
            cloudChannel="5-stable"
            disabled={false}
            onEditorChange={(value) => {
              contentRef.current.value = value;
            }}
            id="blog.hellosu.top/admin"
            init={{
              language: 'zh_CN',
              images_upload_base_path: '',
              images_upload_url: '',
              height: '500px',
              automatic_uploads: true,
              images_upload_handler: async function (
                blobInfo,
                successFun,
                failFun,
              ) {
                const file = blobInfo.blob();
                const re = await uploadFileToQiNiuApi(
                  file,
                  successFun,
                  failFun,
                );
              },
              toolbar1: initToolbar1,
            }}
            inline={false}
            plugins={initPlugins}
          />
        </Form.Item>

        <Form.Item {...buttonLayout} style={{ width: '80%' }}>
          <Button
            type="primary"
            htmlType="submit"
            size="large"
            loading={btnLoading}
          >
            保存
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};
